<?php
declare(strict_types=1);

namespace Service\MemberService;

use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\PointsLog;
use App\Model\BbcModel\PointsOrder;
use App\Model\BbcModel\PointsOrderExtends;
use Service\BaseService;
use Service\ConfigureService\ChannelConfigService;
use Service\MessageService\SmsService;
use Service\Code\Normal;
use Service\MemberService\Volidate\BalanceVolidate;
use Service\ChannelService\StoreConfigService;
use Service\MnBudgetService\MnBudgetService;
use Service\Code\Billcode;
use App\Model\BbcModel\Member;
use Service\PayService\CashPayService;
use App\Model\BbcModel\PointsConfig;
use App\Model\BbcModel\CashRegister;

class BalanceService extends BaseService
{
    /**
     * 充值储值积分
     * @param array $param
     * @return array
     */
     public function chargepoints(array $param): array{
        $param['point'] = $param['points'] ?? '';
        unset($param['points']);
        $res = BalanceVolidate::instance()->checkchargedata($param);
        if($res['code']== Normal::FAIL){
            return $res;
        }
        $cash_register= CashRegister::instance()->info(['id'=>$param['cashregister_id']]);
        if(empty($cash_register)){
            return Normal::returnCode(Normal::FAIL,"未找到收银台");
        }
        $cid       = $param['cid'];
        $mn_sid    = $param['mn_sid'];
        $mid       = $param['mid'];
        $param     = $res['data'];
        $sn        = isset($param['sn']) ? $param['sn'] : Billcode::returnCode('', $param['mn_sid']);
        $time      = time();
        $orderdata = [
            'cid'         => $cid,
            'mn_sid'      => $mn_sid,
            'mid'         => $mid,
            'sn'          => $sn,
            'price_order' => $param['money'],
            'pay_status'  => 1,
            'pay_type'    => 8,
            'cd'          => $time,
            'points'      => $param['point']
        ];
        $mnuser = Mnuser::instance()->info(['id'=>$mn_sid]);
         //获取支付方式
//        $channelPayConfig = ChannelConfigService::instance()->getChannelConfig('pay_way',$cid);
//        $scan_rece_type = (int)($channelPayConfig['type'] ?? 0);
//        
//        if($mnuser['type']==3){
//            //获取店铺支付配置
//            $storePayConfig = StoreConfigService::instance()->getConfig('pay_way', $mn_sid);
//            $scan_rece_type = (int)($storePayConfig['type'] ?? 0);
//        }
        $storePayConfig = StoreConfigService::instance()->getConfig('pay_way', $mn_sid);
        $scan_rece_type = (int)($storePayConfig['type'] ?? 0);
//        if(isset($param['scan_code'])){
//            if(in_array(9, $param['pay_way'])){
//                $scan_rece_type=0;
//            }elseif(in_array(10, $param['pay_way'])){
//                $scan_rece_type=3;
//            }
//        }
        
        //支付手续费
        $pay_fee_config = ChannelConfigService::instance()->getChannelConfig('pay_fee', $cid);
        $pay_fee = ChannelConfigService::instance()->getPayFee((string)($pay_fee_config['fee']??'0'));
        $orderdata['pay_rate'] = $pay_fee;
        $extendsdata           = [
            'cd'              => $time,
            'cid'             => $cid,
            'mn_sid'          => $mn_sid,
            'giveup_money'    => isset($param['giveup_money']) ? $param['giveup_money'] : 0,
            'pay_way'         => implode(',', $param['pay_way']),
            'cash'            => isset($param['cash']) ? $param['cash'] : 0,
            'scan_pay'        => isset($param['scan_pay']) ? $param['scan_pay'] : 0,
            'scan_rece'       => isset($param['scan_rece']) ? $param['scan_rece'] : 0,
            'scan_rece_type'  => $scan_rece_type,
            'pos'             => isset($param['pos']) ? $param['pos'] : 0,
            'storecard'       => isset($param['storecard']) ? $param['storecard'] : 0,
            'storecard_id'    => isset($param['storecard_id']) ? $param['storecard_id'] : 0,
            'balance'         => isset($param['balance']) ? $param['balance'] : 0,
            'coupon'          => isset($param['coupon']) ? $param['coupon'] : 0,
            'points'          => isset($param['points']) ? $param['points'] : 0,
            'cashregister_id' => $param['cashregister_id'],
            'casher'          => $param['casher']
        ];
        PointsOrder::instance()->startTrans();
        try{
            /**
             * 扫码
             */
            if($extendsdata['scan_rece']){
                $extra=[
                    'auth_code'      => $param['scan_code'],
                    'out_trade_no'   => $sn,
                    'body'           => '门店付款',
                    'total_fee'      => $extendsdata['scan_rece'],
                    'cid'            => $cid,
                    'mn_sid'         => $mn_sid,
                    'store_type'     => $mnuser['type'],
                    'buyer'          => '',
                    'order_id'       => '',
                    'scan_rece_type' => $scan_rece_type,
                    'is_order'       => 0,
                    'cash_register'  => $cash_register
                ];
                $user_pay_result = CashPayService::instance()->userPay($cid, $mn_sid,4, $extra);
                if($user_pay_result['code'] == 200){
                    $extendsdata['scan_sn']  = $user_pay_result['data']['transaction_id'];
                    $orderdata['pay_serial'] = $user_pay_result['data']['transaction_id'];
                    $orderdata['pay_time']   = time();
                    $orderdata['is_online']  = 1;
                    $distribute_money        = $mnuser['type']==3?0:bcmul($extendsdata['scan_rece'], $pay_fee, 2);
//                    if($mnuser['type']!=3){
//                        $budgete_extra=[
//                            'type'       => MnBudgetService::TYPE_EXPENDITURE,
//                            'money_type' => MnBudgetService::MONEY_TYPE_BALANCE,
//                            'pay_type'   => 8,
//                            'pay_serial' => $orderdata['pay_serial'],
//                            'sn'         => $sn,
//                            'goods_id'   => 0,
//                            'channel_money'      => $extendsdata['scan_rece'],
//                            'channel_amount'     => 0,
//                            'store_money'      => $distribute_money,
//                            'store_amount'     => bcadd((string)$distribute_money, (string)$mnuser['wallet_income'], 2),
//                            'remark'     => '购买储值积分包收入',
//                            'distribute_money'=>$distribute_money
//                        ];
//                        $mnbudget= MnBudgetService::instance()->addBudget($cid, $mn_sid, $mnuser['mid'], 4, $budgete_extra);
//                        if($mnbudget['code']!= Normal::SUC){
//                            PointsOrder::instance()->rollback();
//                            return $mnbudget;
//                        }
//                    }
                }else{
                    PointsOrder::instance()->rollback();
                    return $user_pay_result;
                }
            }else{
                $orderdata['pay_serial'] = Billcode::returnCode('OT', $param['mn_sid']);
                $orderdata['pay_time']   = time();
                $orderdata['is_online']  = 1;
            }
            $orderres = PointsOrder::instance()->add($orderdata);
            if(!$orderres){
                PointsOrder::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,'新增积分失败');
            }
            $extendsdata['points_order_id'] = $orderres;
            $orderextendsres                = PointsOrderExtends::instance()->add($extendsdata);
            if(!$orderextendsres){
                PointsOrder::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,'订单扩展新增失败');
            }
            $memberpointsres = Member::instance()->where(['mid'=>$mid])->increment('points',$param['point']);
            if(!$memberpointsres){
                PointsOrder::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,'储值卡积分充值失败1');
            }
            Member::instance()->where(['mid'=>$mid])->increment('points_history',$param['point']);
            $pointslog = PointsLog::instance()->add([
                'cid'    => $cid,
                'mid'    => $mid,
                'type'   => 1,
                'points' => $param['point'],
                'mn_sid' => $mn_sid,
                'cd'     => time(),
                'remark' => '购买' . $param['point'] . '储值积分包'
            ]);
            if(!$pointslog){
                PointsOrder::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,'储值卡积分充值失败2');
            }
            $message = [
                'cid'       => $cid,
                'mid'       => $mid,
                'mobile'    => $param['memberinfo']['account'],
                'code'      => '您的' . $param['memberinfo']['account'] . '账户在' . $mnuser['store_name'] . '已购买' . $param['point'] . '储值积分包',
                'temp'      => 'customize'
            ];
            SmsService::instance()->publishMsg($message);
            PointsOrder::instance()->commit();
        }catch (\Exception $e){
            PointsOrder::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,'失败'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'操作成功',['sn'=>$sn,'order_id'=>$orderres]);
    }
    
    /**
     * 储值积分卡充值包获取
     * @param array $param
     * @return array
     */
    public function pointsbackage( array $param): array{
        if(empty($param['mn_sid'])){
            return Normal::returnCode(Normal::FAIL,'缺少店铺id');
        }
        $list = PointsConfig::instance()->lists(['mn_sid'=>$param['mn_sid'],'type'=>1,'_fields_'=>'money,points,position,type','_order_'=>'position asc']);
        if(empty($list)){
            $list = [
                [
                    'money'=>500,
                    'points'=>500,
                    'position'=>1
                ],
                [
                    'money'=>1000,
                    'points'=>1000,
                    'position'=>2
                ],
                [
                    'money'=>2000,
                    'points'=>2000,
                    'position'=>3
                ],
                [
                    'money'=>5000,
                    'points'=>5000,
                    'position'=>4
                ],
                [
                    'money'=>10000,
                    'points'=>10000,
                    'position'=>5
                ],
                [
                    'money'=>20000,
                    'points'=>20000,
                    'position'=>6
                ],
            ];
        }
        foreach ($list as $k=>$v){
            $list[$k]['points'] = round($v['points'],2);
        }
        return Normal::returnCode(Normal::SUC,'请求成功',$list);
    }

}
